package com.example.demolbclientwithouteureka;



import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.util.Map;

@RestController
public class MyWebClient {
    Logger logger= LoggerFactory.getLogger(getClass());

    @Autowired
    LoadBalancerClient loadBalancerClient;

    //从Eureka中根据服务名称选择第一一个可用服务
    @RequestMapping(value="/ulogin1",produces = "application/json;charset=UTF-8")
    public Map userlogin1() {
        //启用负载均衡
        ServiceInstance serviceInstance=loadBalancerClient.choose("userlogin");

        String serviceUrl = serviceInstance.getUri().toString();
        System.out.println(serviceUrl);
        RestTemplate restTemplate = new RestTemplate();
        logger.info("spring-cloud-loadbalancer 负载均衡1");
        return restTemplate.getForObject(serviceUrl + "/login", Map.class);
    }


    @Autowired
    RestTemplate restTemplate;
    //启用ribbon负载均衡策略
    @RequestMapping(value="/ulogin2",produces = "application/json;charset=UTF-8")
    public Map userlogin2() {

        logger.info("spring-cloud-loadbalancer 负载均衡2");
        return restTemplate.getForObject("http://userlogin/login", Map.class);
    }

    @Autowired
    private WebClient webClient;

    @RequestMapping(value="/ulogin3",produces = "application/json;charset=UTF-8")
    public Mono<Map> userlogin3() {
        String url = "http://userlogin/login";
        Mono<Map> result = webClient.get().uri(url)
                .retrieve().bodyToMono(Map.class);
        return result;
    }

}

